package com.zhujiaji.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Calendar;

/**
 * @author 朱佳吉
 * @date 2024/3/16 21:36
 */
public class JwtUtil {

    private static final String sign = "XIAOZHU";

    public static String generatorToken(Integer userId) {
        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.MINUTE, 30);
        return JWT.create().withClaim("userId", userId)
                .withExpiresAt(instance.getTime())
                .sign(Algorithm.HMAC256(sign));
    }

    public static Integer parseToken(String token) {
        JWTVerifier verifier = JWT.require(Algorithm.HMAC256(sign)).build();
        DecodedJWT verify = verifier.verify(token);
        return verify.getClaim("userId").asInt();
    }
}
